<template>
    <div class="container">
        <van-tabs v-model:active="active" @change="handleTabChange">
            <van-tab v-for="category in categoryList" :key="category.cateid" :title="category.catename">
                <van-swipe :autoplay="3000000" lazy-render>
                    <van-swipe-item v-for="(image, imgIndex) in images" :key="imgIndex">
                        <nuxt-link :to="'/news/' + image.newsid" class="flex">
                            <div class="slide-content">
                                <div class="slide-img">
                                    <van-image :src="image.breviaryimges" fit="cover" height="210" width="100%" />
                                </div>
                                <div class="slide-text pd30">
                                    <h2 class="title">
                                        {{ image.title }}
                                    </h2>
                                    <p class="date">
                                        {{ safeFormatRelativeTime(image.releasetime) }}
                                    </p>
                                </div>
                            </div>
                        </nuxt-link>
                    </van-swipe-item>
                </van-swipe>
                <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
                    <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                        <van-cell v-for="newsItem in list" :key="newsItem.id" class="news-box">
                            <template v-if="newsItem.newstype === 'special'">
                                <!-- special 类型：大卡片展示（示例） -->
                                <nuxt-link
                                    :to="{ path: '/special/' + newsItem.newsid, query: { cid: newsItem.cateid } }"
                                    class="flex special-card">
                                    <div class="special-img">
                                        <van-image :src="newsItem.breviaryimges || safeImageSrc(newsItem.id)"
                                            width="100%" height="72" fit="cover" />
                                    </div>
                                </nuxt-link>
                            </template> 
                            <template v-else>
                                <!-- 普通 news 类型展示（原有结构） -->
                                <nuxt-link :to="{ path: '/news/' + newsItem.newsid, query: { cid: newsItem.cateid } }"
                                    class="flex">
                                    <div class="news-text">
                                        <h2 class="title">{{ newsItem.title }}</h2>
                                        <p class="date">{{ safeFormatRelativeTime(newsItem.releasetime) }} · {{
                                            newsItem.author }}</p>
                                    </div>
                                    <div class="news-img">
                                        <van-image :src="newsItem.breviaryimges || safeImageSrc(newsItem.id)"
                                            width="128" height="72" fit="cover" />
                                    </div>
                                </nuxt-link>
                            </template>
                        </van-cell>
                    </van-list>
                </van-pull-refresh>
            </van-tab>
        </van-tabs>

    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'; 

// 接口类型定义（与后端返回字段匹配）
interface NewsItem {
    id: string;
    newsid: string;
    title: string;
    summary?: string;
    breviaryimges?: string;
    releasetime?: string;
    author?: string;
    cateid?: number | string;
    newstype?: string;
}

interface Category {
    cateid: number;
    catename: string;
}

// 首先定义所有响应式变量，确保模板渲染时可用
const active = ref(1);
const categoryList = ref<Category[]>([]);
const images = ref<any[]>([]);
// 滚动加载和刷新相关状态
const list = ref<NewsItem[]>([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
// 当前选中的分类ID（来自 category.cateid）
const currentCategoryId = ref<number>(0);

//时间格式化
const dayjs = useDayjs();

const safeFormatRelativeTime = (time: string | null | undefined) => {
  if (!time) return '';
  const now = dayjs();
  const target = dayjs(time);
  
  // 如果是当天时间，显示相对时间（如 "2 小时前"）
  if (target.isSame(now, 'day')) {
    return target.fromNow();
  } 
  // 非当天时间，显示完整年月日（如 "2023-01-01"）
  return target.format('YYYY-MM-DD');
};


// 获取新闻分类数据
const fetchNewsCategory = async () => {
    try {
        const response = await $fetch('/api/news/category');
        if (response?.data && Array.isArray(response.data)) {
            // 对后端字段做最小映射保证类型一致
            categoryList.value = response.data.map((c: any) => ({
                cateid: Number(c.cateid),
                catename: String(c.catename)
            }));
        }
    } catch (error) {
        console.error('获取新闻分类失败:', error);
    }
};
 

// 获取新闻数据的函数
const fetchNewsList = async (pageindex: number = 1, append: boolean = false, cateid?: number) => {
    try {
        // 简化参数构建，直接传递cateid
        const queryParams: any = { pageindex, pagesize: pageSize.value };

        // 只要cateid存在，就添加到参数中
        if (cateid !== undefined) {
            queryParams.cateid = String(cateid);
        }

        console.log('fetchNewsList请求参数:', queryParams);

        const response = await $fetch('/api/news/newslist', {
            params: queryParams
        });

        if (response?.data && Array.isArray(response.data)) {
            // 有时后端会返回不同字段结构，这里尽量保持我们需要的字段
            const normalized = response.data.map((n: any) => ({
                id: String(n.id || n.newsid || n.articleid || ''),
                newsid: String(n.newsid || n.id || ''),
                title: String(n.title || n.subject || ''),
                summary: String(n.summary || n.description || n.intro || ''),
                breviaryimges: n.breviaryimges || n.picurl || n.thumb || '',
                releasetime: n.releasetime || n.posttime || '',
                author: n.author || n.source || '',
                cateid: n.cateid || n.classid || undefined,
                newstype: n.newstype || n.type || n.contenttype || ''
            }));

            if (append) {
                list.value = [...list.value, ...normalized];
                console.log('list.value:', list.value);
            } else {
                list.value = normalized;
            }
            // 如果返回的数据少于请求的数量，说明没有更多数据了
            finished.value = normalized.length < pageSize.value;
            return normalized.length;  
        }
    } catch (error) {
        console.error('获取新闻数据失败:', error);
    }
    return 0;
};

// 处理标签切换
const handleTabChange = async (activeIndex: number) => {
    if (!categoryList.value[activeIndex]) return;
    // 重置状态
    finished.value = false;
    currentPage.value = 1;
    loading.value = true;

    // 获取当前分类的ID并转换为数字类型，处理可能的NaN
    const categoryId = Number(categoryList.value[activeIndex].cateid) || 0;
    currentCategoryId.value = categoryId;
    console.log('切换分类ID:', categoryId);

    try {
        await fetchNewsList(1, false, categoryId);
    } finally {
        loading.value = false;
    }
};

// 加载更多数据
const onLoad = async () => {
    if (finished.value) {
        loading.value = false;
        return;
    } 
    try {
        // 加载下一页数据
        const nextPage = currentPage.value + 1;
        const loadedCount = await fetchNewsList(nextPage, true, currentCategoryId.value);
        if (loadedCount > 0) {
            currentPage.value = nextPage;
        }
    } catch (error) {
        console.error('加载更多新闻失败:', error);
    } finally {
        loading.value = false;
    }
};

// 刷新数据
const onRefresh = async () => {
    // 重置状态
    finished.value = false;
    currentPage.value = 1;

    // 重新获取第一页数据
    try {
        await fetchNewsList(1, false, currentCategoryId.value);
    } catch (error) {
        console.error('刷新新闻数据失败:', error);
    } finally {
        // 结束下拉刷新以及加载状态
        refreshing.value = false;
        loading.value = false;
    }
};



// 组件挂载后初始化数据
onMounted(async () => {
    // 获取轮播图数据
    const homeBanner = await $fetch('/api/banner/homeBanner');

    // 提取banner图片URL
    if (homeBanner?.data && Array.isArray(homeBanner.data)) {
        images.value = homeBanner.data[1];
        console.log(images.value);
    } else {
        // 数据结构不正确时使用默认图片
        images.value = ['/swiper1.png', '/swiper2.png', '/swiper3.png'];
    }

    // 获取新闻分类
    await fetchNewsCategory();

    // 等分类数据加载完成后再加载新闻列表
    if (categoryList.value.length > 0) {
        // 存储当前active的分类ID，确保转换为数字类型并处理可能的NaN
        const activeCategoryId = Number(categoryList.value[active.value]?.cateid ?? 0) || 0;
        currentCategoryId.value = activeCategoryId;
        console.log('初始化分类ID:', activeCategoryId);
        // 使用当前分类ID加载新闻列表
        loading.value = true;
        try {
            await fetchNewsList(1, false, activeCategoryId);
        } finally {
            loading.value = false;
        }
    }
});

// 生成安全的默认图片路径
const safeImageSrc = (id?: string) => {
    const n = Number(id || '0') || 0;
    const idx = (n % 3) + 1;
    return `/new${idx}.jpg`;
};
</script>

<style scoped>
.slide-content {
    position: relative;
    flex: 1;
}

:deep(.van-swipe) {
    font-size: 0;
}

.slide-text {
    position: absolute;
    bottom: 8px;
    left: 0;
    width: calc(100% - 30px);
    color: #fff;
}

.slide-text .title {
    font-size: 17px;
    height: 52px;
    line-height: 26px;
    text-shadow: 1px 1px 0px rgba(0, 0, 0, 0.5);
}

.slide-text .date {
    font-size: 10px;
    color: rgba(255, 255, 255, 0.8);
}

.news-box :deep(.van-cell__value) {
    text-align: left;
}

.special-card {
    flex-direction: column;
    align-items: stretch;
}

.special-img {
    width: 100%;
    overflow: hidden;
}

.special-body .title {
    margin: 8px 0 6px;
}

.special-body .summary {
    color: #666;
    font-size: 14px;
    margin-bottom: 8px;
}
</style>